package com.example.foodsy.config;

import com.example.foodsy.filter.JwtAuthenticationFilter;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.core.GrantedAuthorityDefaults;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity // 支持方法级别的权限控制
public class SecurityConfig {

    @Resource
    private JwtAuthenticationFilter jwtAuthFilter;

    // 配置密码加密方式（BCrypt）
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    // 配置认证管理器
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }

    // 配置安全过滤链（接口权限控制）
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf(csrf -> csrf.disable()) // 关闭CSRF（前后端分离场景）
                .sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 无状态会话（JWT不需要session）
                )
                .authorizeHttpRequests(auth -> auth
                        // 公开接口（无需登录）
                        .requestMatchers("/admin/login","/company-info/login","/trace/query").permitAll()
                        // 企业修改密码接口（仅COMPANY角色可访问）
                        .requestMatchers("/company-info/updatePassword").hasRole("COMPANY")
                        // 零售商确认产品批号接口（仅COMPANY角色可访问）
                        .requestMatchers("/company-info/reta/batch/confirm/{rbId}").hasRole("COMPANY")
                        // 管理员接口（仅ADMIN角色可访问）
                        .requestMatchers("/company-info/**").hasRole("ADMIN")
                        // 其他接口需认证
                        .anyRequest().authenticated()
                )
                // 添加JWT过滤器（在用户名密码过滤器之前执行）
                .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

    @Bean
    public GrantedAuthorityDefaults grantedAuthorityDefaults() {
        return new GrantedAuthorityDefaults(""); // 移除ROLE_前缀
    }
}